import React, {useEffect, useState} from "react";
import {TabView, Text} from "react-native-elements";
import {Dimensions, ScrollView, StyleSheet, TextInput, TouchableHighlight, View} from "react-native";
import {getChainBaseByChainID, getTokenByChainID, nowWallet} from "./smartxL2Libs/L2_Data";
import {SvgXml} from "react-native-svg";
import {fontSize_12, fontSize_14, fontSize_15, fontSize_16, fontSize_20} from "./theme";
import {Tab} from "react-native-elements/dist/tab/Tab";
import {copySvgXml, searchSvgXml, tranInSvgXml, tranOutSvgXml} from "../libs/svgXml";
import {Net} from "../screens/axios";
import {timeFormat} from "../libs/utils";
import BigNumber from "bignumber.js";
import {getBalance, getTokenBalance, getTransferList_ETH} from "./smartxL2Libs/smartxL2Web3";
import {checkAddressEq} from "./smartxL2Libs/L2_utils";
import {Avatar} from "react-native-elements/dist/avatar/Avatar";
import {ethers} from "ethers";
import {formartMoney} from "../libs/helpers";

const {width,height,scale} = Dimensions.get("window");

const L2_TxList = ({navigation,route}:any) => {
    const [tokenAddress,setTokenAddress] = useState(route?.params?.tokenAddress || "")
    const [name,setName] = useState(route?.params?.name)
    const [img,setImg] = useState(route?.params?.img)
    const [balance,setBalance] = useState({balance:"",valueOfCNY: "", valueOfUSDT: "",})
    const [Asset_Index, setAsset_Index] = useState(0);
    const [transferList,setTransferList] = useState([]);
    const [transferFrom,setTransferFrom] = useState([])//转出
    const [transferTo,setTransferTo] = useState([])//转入
    const [decimals,setDecimals] = useState("9")
    useEffect(()=>{
        navigation.setOptions({
            title:"交易记录"
        })
        initBalance()
        getTransferList();
    },[])
    const getTransferList = async () => {
        let tranList = await getTransferList_ETH(nowWallet.address,nowWallet.chainID,tokenAddress)

        let tranListFrom = [];
        let tranListTo = [];
        let tranListTemp = [];
        for(let i = 0 ; i < tranList.length ; i++ )
        {
            // console.log(tranList[i].from,tranList[i].from.toLowerCase() === nowWallet.address.toLowerCase())
            if(tranList[i].from.toLowerCase() === nowWallet.address.toLowerCase())
            {
                tranListFrom.push(tranList[i])
            }
            else
            {
                tranListTo.push(tranList[i])
            }
            tranListTemp.push(tranList[i])
        }
        setTransferList(tranListTemp.reverse())
        setTransferFrom(tranListFrom.reverse())
        setTransferTo(tranListTo.reverse())


    }
    const initBalance = async () => {
        console.log(tokenAddress)
        console.log(!tokenAddress)
        if(!tokenAddress)
        {
            let addressBalance = await getBalance(nowWallet.address);
            let valueOfCNY = (new BigNumber(addressBalance)).multipliedBy(0.0026).toString();
            let balanceTemp = {balance:new BigNumber(addressBalance).dp(4,1).toString(),valueOfCNY,valueOfUSDT: ""};
            setBalance(balanceTemp)
            return ;
        }
        let balance = await getTokenBalance(tokenAddress);
        let tokenTemp = await getTokenByChainID(nowWallet.chainID,tokenAddress,nowWallet.address);
        let valueOfCNY = "0"
        if(tokenTemp)
        {
            let balanceTemp = {balance:tokenTemp.balance,valueOfCNY,valueOfUSDT: ""};
            setBalance(balanceTemp);
        }
        if(balance.success && tokenTemp)
        {
            valueOfCNY = (new BigNumber(balance.data.balance)).multipliedBy(tokenTemp?.tokenPrice_CNY).toString();
            let balanceTemp = {balance:balance.data.balance,valueOfCNY,valueOfUSDT: ""};
            setBalance(balanceTemp);
            return
        }
        return ;


    }

    return (
        <View style={styles.container}>
            <View style={styles.tokenTitle}>
                <Avatar source={((typeof img)==="number")?img:{uri:img}} rounded={true} activeOpacity={0.7}
                        containerStyle={{borderWidth: 0 / scale}}/>
                <Text style={{fontSize:fontSize_20,marginLeft:15}}>{name}</Text>
                <View style={{flex:1}}/>
                <Text style={{fontSize:fontSize_15,color:"#a4a4a4"}}>项目详情 ></Text>
            </View>
            <View style={styles.assetBalance}>
                <Text style={{fontSize:fontSize_16}}>资产余额</Text>
                <View style={styles.rightAsset}>
                    <Text style={{fontSize:fontSize_15}}>
                        {balance.balance}
                    </Text>
                    <Text style={{fontSize:fontSize_12,color:"#939393"}}>
                        ≈ ¥ {balance.valueOfCNY}
                    </Text>
                </View>
            </View>
            <View style={styles.divider_10}/>
            <View style={styles.tab_header}>
                <View style={styles.tabStyle}>
                    <Tab value={Asset_Index} variant={'default'} onChange={(i) => {
                        setAsset_Index(i)
                    }}
                         disableIndicator={false}
                         indicatorStyle={styles.tabIndicatorStyle}
                    >
                        <Tab.Item title={"全部"}
                                  background={null}
                                  buttonStyle={{padding: 0, margin: 0}}
                                  containerStyle={{backgroundColor: "white"}}
                                  titleProps={{
                                      style: {
                                          padding: 0,
                                          marginLeft: -25,
                                          color: "black",
                                          fontSize: fontSize_16,
                                          lineHeight: 31
                                      }
                                  }}
                        />
                        <Tab.Item title="转出"
                                  background={null}
                                  buttonStyle={{padding: 0, margin: 0,}}
                                  containerStyle={{backgroundColor: "white"}}
                                  titleProps={{
                                      style: {
                                          padding: 0,
                                          marginLeft: -25,
                                          color: "black",
                                          fontSize: fontSize_16,
                                          lineHeight: 31
                                      }
                                  }}
                        />
                        <Tab.Item title="转入"
                                  background={null}
                                  buttonStyle={{padding: 0, margin: 0,}}
                                  containerStyle={{backgroundColor: "white"}}
                                  titleProps={{
                                      style: {
                                          padding: 0,
                                          marginLeft: -25,
                                          color: "black",
                                          fontSize: fontSize_16,
                                          lineHeight: 31
                                      }
                                  }}
                        />
                    </Tab>
                </View>
                <View style={{flexDirection:"row",alignItems:"center"}}>
                    <TextInput style={styles.search_container}
                               placeholder={"搜索"}
                    />
                    <SvgXml xml={searchSvgXml} width={20} height={20}
                            style={{position: "absolute", left: 2, top: 5}}/>
                </View>
            </View>
            <View style={{width:"100%",flex:1}}>
                <TabView value={Asset_Index} animationType={"spring"}>
                    <TabView.Item style={{width:width-30}}>
                        <ScrollView style={{width:"100%"}} contentContainerStyle={{width:"100%",paddingBottom:270}} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false}>
                        {
                            transferList.length > 0?
                                transferList.map((item,index)=>(
                                    <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                                        navigation.navigate("L2_transferDetail",{item,name,tokenAddress})
                                    }} style={{width:"100%"}} key={"transferList_"+index}>
                                        <View style={{flexDirection:"row",width:"100%",paddingTop:10,paddingBottom:10,alignItems:"center",borderBottomWidth:5/scale,borderBottomColor:"#f6f6f6"}} >
                                            <View style={{backgroundColor:checkAddressEq(item.from,nowWallet.address)?"#37b58b":"#1d82fe",width:25,height:25,borderRadius:12.5,alignItems:"center",justifyContent:"center"}}>
                                                {
                                                    checkAddressEq(item.from,nowWallet.address)?
                                                        <SvgXml xml={tranOutSvgXml("#fff")} width={15} height={15}/>:
                                                        <SvgXml xml={tranInSvgXml("#fff")} width={15} height={15}/>
                                                }
                                            </View>
                                            <View style={{flex:1,marginLeft:10,height:50,justifyContent:"center"}}>
                                                <View style={{flexDirection:"row",alignItems:"center",paddingBottom:5}}>
                                                    <Text style={{fontSize:fontSize_14,textAlignVertical:"center",paddingRight:10}}>{item.hash.slice(0,5)}...{item.hash.slice(-5)}</Text>
                                                    <SvgXml xml={copySvgXml} width={fontSize_14} height={fontSize_14} onPress={()=>{
                                                        console.log("copy")
                                                    }}/>
                                                </View>
                                                <Text style={{fontSize:fontSize_12,color:"#8d8d8d",textAlignVertical:"center"}}>{timeFormat(Number(item.timeStamp)*1000)}</Text>
                                            </View>
                                            <Text style={{maxWidth:"40%",fontSize:fontSize_15,fontWeight:"normal",color:checkAddressEq(item.from,nowWallet.address)?"#3eb58c":"#1d70db"}}>
                                                {checkAddressEq(item.from,nowWallet.address)?"-":"+"} {!tokenAddress?formartMoney(ethers.utils.formatEther(item.value),4):(new BigNumber(item.value).div(new BigNumber(10).pow(item.tokenDecimal)).toFixed(4))} {name}
                                            </Text>
                                        </View>
                                    </TouchableHighlight>
                                )):null
                        }
                        </ScrollView>
                    </TabView.Item>
                    <TabView.Item style={{width:width-30}}>
                        <ScrollView style={{width:"100%"}} contentContainerStyle={{width:"100%",paddingBottom:270}} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false}>
                        {
                            transferFrom.length > 0?
                                transferFrom.map((item,index)=>(
                                    <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                                        navigation.navigate("L2_transferDetail",{item,name,tokenAddress})
                                    }} style={{width:"100%"}} key={"transferFrom_"+index}>
                                        <View style={{flexDirection:"row",width:"100%",paddingTop:10,paddingBottom:10,alignItems:"center",borderBottomWidth:5/scale,borderBottomColor:"#f6f6f6"}} >
                                            <View style={{backgroundColor:checkAddressEq(item.from,nowWallet.address)?"#37b58b":"#1d82fe",width:25,height:25,borderRadius:12.5,alignItems:"center",justifyContent:"center"}}>
                                                {
                                                    checkAddressEq(item.from,nowWallet.address)?
                                                        <SvgXml xml={tranOutSvgXml("#fff")} width={15} height={15}/>:
                                                        <SvgXml xml={tranInSvgXml("#fff")} width={15} height={15}/>
                                                }
                                            </View>
                                            <View style={{flex:1,marginLeft:10,height:50,justifyContent:"center"}}>
                                                <View style={{flexDirection:"row",alignItems:"center",paddingBottom:5}}>
                                                    <Text style={{fontSize:fontSize_14,textAlignVertical:"center",paddingRight:10}}>{item.hash.slice(0,5)}...{item.hash.slice(-5)}</Text>
                                                    <SvgXml xml={copySvgXml} width={fontSize_14} height={fontSize_14} onPress={()=>{
                                                        console.log("copy")
                                                    }}/>
                                                </View>
                                                <Text style={{fontSize:fontSize_12,color:"#8d8d8d",textAlignVertical:"center"}}>{timeFormat(Number(item.timeStamp)*1000)}</Text>
                                            </View>
                                            <Text style={{maxWidth:"40%",fontSize:fontSize_15,fontWeight:"normal",color:checkAddressEq(item.from,nowWallet.address)?"#3eb58c":"#1d70db"}}>
                                                {checkAddressEq(item.from,nowWallet.address)?"-":"+"} {!tokenAddress?formartMoney(ethers.utils.formatEther(item.value),4):(new BigNumber(item.value).div(new BigNumber(10).pow(item.tokenDecimal)).toFixed(4))} {name}
                                            </Text>
                                        </View>
                                    </TouchableHighlight>
                                )):null
                        }
                        </ScrollView>
                    </TabView.Item>
                    <TabView.Item style={{width:width-30}}>
                        <ScrollView style={{width:"100%"}} contentContainerStyle={{width:"100%",paddingBottom:270}} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false}>
                        {
                            transferTo.length > 0?
                                transferTo.map((item,index)=>(
                                    <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                                        navigation.navigate("L2_transferDetail",{item,name})
                                    }} style={{width:"100%"}} key={"transferTo_"+index}>
                                        <View style={{flexDirection:"row",width:"100%",paddingTop:10,paddingBottom:10,alignItems:"center",borderBottomWidth:5/scale,borderBottomColor:"#f6f6f6"}} >
                                            <View style={{backgroundColor:checkAddressEq(item.from,nowWallet.address)?"#37b58b":"#1d82fe",width:25,height:25,borderRadius:12.5,alignItems:"center",justifyContent:"center"}}>
                                                {
                                                    checkAddressEq(item.from,nowWallet.address)?
                                                        <SvgXml xml={tranOutSvgXml("#fff")} width={15} height={15}/>:
                                                        <SvgXml xml={tranInSvgXml("#fff")} width={15} height={15}/>
                                                }
                                            </View>
                                            <View style={{flex:1,marginLeft:10,height:50,justifyContent:"center"}}>
                                                <View style={{flexDirection:"row",alignItems:"center",paddingBottom:5}}>
                                                    <Text style={{fontSize:fontSize_14,textAlignVertical:"center",paddingRight:10}}>{item.hash.slice(0,5)}...{item.hash.slice(-5)}</Text>
                                                    <SvgXml xml={copySvgXml} width={fontSize_14} height={fontSize_14} onPress={()=>{
                                                        console.log("copy")
                                                    }}/>
                                                </View>
                                                <Text style={{fontSize:fontSize_12,color:"#8d8d8d",textAlignVertical:"center"}}>{timeFormat(Number(item.timeStamp)*1000)}</Text>
                                            </View>
                                            <Text style={{maxWidth:"40%",fontSize:fontSize_15,fontWeight:"normal",color:checkAddressEq(item.from,nowWallet.address)?"#3eb58c":"#1d70db"}}>
                                                {checkAddressEq(item.from,nowWallet.address)?"-":"+"} {!tokenAddress?formartMoney(ethers.utils.formatEther(item.value),4):(new BigNumber(item.value).div(new BigNumber(10).pow(item.tokenDecimal)).toFixed(4))} {name}
                                            </Text>
                                        </View>
                                    </TouchableHighlight>
                                )):null
                        }
                        </ScrollView>
                    </TabView.Item>
                </TabView>
            </View>
            <View style={styles.transferContainer}>
                <TouchableHighlight underlayColor={"#37b58b"} onPress={()=>{
                    navigation.navigate("L2_transfer",{tokenAddress,tokenName:name})
                }}
                                    style={[styles.transferBTN,styles.backgroundFrom,styles.marginRight10]}>
                    <Text style={styles.transferTitle}>转账</Text>
                </TouchableHighlight>
                <TouchableHighlight underlayColor={"#1d82fe"} onPress={()=>{
                    navigation.navigate("L2_Receive",{address:nowWallet.address})
                }}
                                    style={[styles.transferBTN,styles.backgroundTo]}>
                    <Text style={styles.transferTitle}>收款</Text>
                </TouchableHighlight>

            </View>


        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 10,
        paddingRight: 20,
        backgroundColor: "white"
    },
    tokenTitle:{
        width:"100%",
        paddingTop:10,
        paddingBottom:10,
        borderBottomWidth:5/scale,
        borderBottomColor:"#f6f6f6",
        flexDirection:"row",
        alignItems:"center"
    },
    assetBalance:{
        width:"100%",
        flexDirection:"row",
        justifyContent:"space-between",
        alignItems:"center",
        paddingTop:10,
        paddingBottom:10
    },
    rightAsset:{
        flexDirection:"column",
        alignItems:"flex-end",
    },
    divider_10:{
        width:width,
        height:10,
        backgroundColor:"#f6f6f6"
    },
    tabStyle: {
        width: 180,
        alignItems: "flex-start"
    },
    tabIndicatorStyle: {
        height: 2,
        backgroundColor: "black",
        width: 20,
        left: 8
    },
    tab_header: {
        width: "100%",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        backgroundColor: "white",
        height: 50,
        borderBottomWidth:5/scale,
        borderBottomColor:"#f6f6f6"
    },
    search_container: {
        width: 90,
        height: 30,
        backgroundColor: "#f5f6f8",
        fontSize: fontSize_12,
        flexDirection: "row",
        alignItems: "center",
        padding: 0,
        borderRadius: 14,
        paddingRight: 14,
        paddingLeft: 30,
        marginRight: 10,
    },
    transferContainer:{
        height:60,
        width:width,
        padding:10,
        marginLeft:10,
        paddingRight:20,
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"space-between",
        borderTopWidth:2/scale,
        borderTopColor:"#f8f8f9",
        backgroundColor: "#fcfdff",
    },
    transferBTN:{
        flex:1,
        height:"100%",
        alignItems:"center",
        justifyContent:"center",
        borderRadius:10,
    },
    transferTitle:{
        fontSize:fontSize_15,
        color:"white"
    },
    backgroundFrom:{
        backgroundColor:"#37b58b"
    },
    backgroundTo:{
        backgroundColor:"#1d82fe",
    },
    marginRight10:{
        marginRight:10
    }
})
export default L2_TxList;


